<?php
set_include_path ( $_SERVER ['DOCUMENT_ROOT'] );
include_once 'admin/includes/functions/admin-functions.php';
global $DBobject, $CONFIG, $SMARTY;

//LOAD PENDING BANK TRANSFER - PAYMENT RECORD
$arr = explode("/", $_REQUEST["arg1"]);
if($arr[0] == 'members' && !empty($arr[2])){
	$sql= "SELECT * FROM tbl_payment LEFT JOIN tbl_user ON user_id = payment_user_id WHERE payment_deleted IS NULL AND payment_status = 'P' AND payment_response_cardscheme = 'Bank Transfer' AND payment_id = :payment_id";
	$params = array('payment_id'=>$arr[2]);
	if($res = $DBobject->wrappedSql($sql, $params)){
		$SMARTY->assign("data", $res[0]);
		
		$surchargePer = floatval($CONFIG->payment_gateway->surcharge_percentage);
		$SMARTY->assign("surcharge_percentage", $surchargePer);
		$chargedAmount = $res[0]['payment_charged_amount'];
		$surcharge = round($chargedAmount * $surchargePer / 100,2);
		$SMARTY->assign("surcharge_amount", $surcharge);
		$chargedAmount = round($chargedAmount + $surcharge, 2);
		$SMARTY->assign("total", $chargedAmount);
	}
}



//CHANGE PAYMENT METHOD
if(!empty($_POST['payment_id']) && !empty($_POST['cc'])){
	$error = "Session has expired. Please refresh.";
	$referer = parse_url($_SERVER['HTTP_REFERER']);
	if( $referer['host'] == $GLOBALS['HTTP_HOST'] && checkToken('admin', $_POST["formToken"])){
		$response = false;
		$url = false;
		
		switch ($_POST['action']) {
			case 'ChangePaymentMethod':

				$sql= "SELECT * FROM tbl_payment LEFT JOIN tbl_user ON user_id = payment_user_id WHERE payment_deleted IS NULL AND payment_status = 'P' AND payment_response_cardscheme = 'Bank Transfer' AND payment_id = :payment_id";
				$params = array('payment_id'=>$_POST['payment_id']);
				if($res = $DBobject->wrappedSql($sql, $params)){
					$data= $res[0];
					$userArr = array (
	    				"id" => $data['user_id'],
	    				"gname" => $data['user_gname'],
	    				"surname" => $data['user_surname'],
	    				"email" => $data['user_email']
					);
					$order_cartId = $data['payment_cart_id'];
					$enrol_obj =  new Enrolment();
					$orderNumber = $data['payment_transaction_no'];
						
					$total = $data['payment_total'];
					$chargedAmount = $data['payment_charged_amount'];
					$surchargePer = floatval($CONFIG->payment_gateway->surcharge_percentage) / 100;
			
					$surcharge = round($chargedAmount * $surchargePer,2);
					$chargedAmount = round($chargedAmount + $surcharge, 2);
					$total = round($total + $surcharge, 2);
			
			
					$params = array(
							'payment_billing_address_id' => $data['payment_billing_address_id'],
							'payment_shipping_address_id' => $data['payment_shipping_address_id'],
							'payment_transaction_no' => $orderNumber,
							'payment_cart_id' => $order_cartId,
							'payment_user_id' => $userArr['id'],
							'payment_subtotal' => $data['payment_subtotal'],
							'payment_discount' => $data['payment_discount'],
							'payment_shipping_fee' => $data['payment_shipping_fee'],
							'payment_shipping_method' => $data['payment_shipping_method'],
							'payment_shipping_comments' =>  $data['payment_shipping_comments'],
							'payment_status' => 'P',
							'payment_additional_description' =>  $data['payment_additional_description'],
							'payment_additional' =>  $data['payment_additional'],
							'payment_surcharge' =>  $surcharge,
							'payment_payee_name' => $_POST['cc']['name'],
							'payment_charged_amount' => $chargedAmount,
							'payment_total' => $total,
							'payment_gst' => $data['payment_gst'],
							'payment_method' => '',
							'next_payment_date' => $data['next_payment_date']
					);
			
					$pay_obj = new PaymentCommBank($params);
					$response = false;
			
					try{
						$CCdata =  array('amount'=>$chargedAmount);
						$CCdata = array_merge($_POST['cc'], $CCdata);
						$pay_obj->PreparePayment($CCdata);
			
							
						// ORDER STATUS
						$status = 3; // Approved - Credit Card - Partial
						if($chargedAmount == $total){
							$status = 2; // Approved - Credit Card - Full
						}
			
						//CREDIT CARD PAYMENT
						if(!empty($chargedAmount) && ($total > 0)){
							$response = $pay_obj->Submit();
							$paymentId = $pay_obj->GetPaymentId();
						}
					}catch (Exception $e){
						$error = 'Payment Error: ' .$e;
						break;
					}
			
						
					if($response){// PAYMENT SUCCESS
							
						// SET ORDER STATUS
						$pay_obj->SetOrderStatus($paymentId, $status, $_SESSION['user']['admin']["id"]);
			
						$order = $enrol_obj->GetDataCart($order_cartId);
						$payment = $pay_obj->GetPaymentRecord($paymentId);
						$orderItems = $enrol_obj->GetDataProductsOnCart($order_cartId);
							
						try{
							
							$params = array(":old_payment_id"=>$_POST['payment_id'], ":new_payment_id"=>$paymentId);
							
							// UPDATE ENROLMENT RECORDS
							$sql = "UPDATE tbl_enrolment SET enrolment_payment_id = :new_payment_id, enrolment_modified = now()	WHERE enrolment_deleted IS NULL AND enrolment_payment_id = :old_payment_id";
							$DBobject->wrappedSql($sql,$params);
							
							// UPDATE DEBT RECORDS
							$sql = "UPDATE tbl_debt SET debt_payment_id = :new_payment_id, debt_modified = now() WHERE debt_deleted IS NULL AND debt_payment_id = :old_payment_id";
							$DBobject->wrappedSql($sql,$params);
							
							// DELETE OLD PAYMENT RECORD
							$sql = "UPDATE tbl_payment SET payment_deleted = now() WHERE payment_deleted IS NULL AND payment_id = :old_payment_id";
							$DBobject->wrappedSql($sql, array(":old_payment_id"=>$_POST['payment_id']));
							
						}catch(Exception $e){
							$error = 'Error: Enrolments cannot be updated - ' .$e;
							$to = "readysteadygokids@gmail.com-dev,online@them.com.au,readysteadygokids@gmail.com-dev";
							sendMail($to, (string) $CONFIG->company->name, 'noreply@' . str_replace ( "www.", "", $GLOBALS['HTTP_HOST'] ), 'Back-end (A)CHANGING PAYMENT ERROR ', "Order: ".$order_cartId."</br> Session: ".print_r($_SESSION,TRUE));
						}
							
						try{
							$member_obj = new Member();
							$addressArr = $member_obj->GetAddress($data['payment_shipping_address_id']);
							
							// SEND CONFIRMATION EMAIL
							$SMARTY->assign("user",$userArr);
							$SMARTY->assign('shipping',$addressArr);
							$SMARTY->assign('order',$order);
							$SMARTY->assign('payment',$payment);
							$SMARTY->assign('orderItems',$orderItems);
							$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
							$domain = $protocol . $GLOBALS['HTTP_HOST'];
							$SMARTY->assign('DOMAIN', $domain);
							$SMARTY->assign('status', $status);
							$SMARTY->assign('nextpayment', $_POST['nextpayment']);
								
							// ================= Custom Messages ================
							$sql = "SELECT email_additional_content FROM tbl_email_additional WHERE email_additional_id = :id ";
							if($res = $DBobject->wrappedSql ( $sql, array(':id' => 11)) ){//CreditCard
								$message = unclean($res[0]['email_additional_content']);
								$SMARTY->assign('creditMessage', $message);
							}
							// ==================================================
			
							$COMP = json_encode($CONFIG->company);
							$SMARTY->assign('COMPANY', json_decode($COMP,TRUE));
			
							$to = $userArr['email'];
							//$bcc = (string) $CONFIG->company->email_orders;
			
							$from = (string) $CONFIG->company->name;
							$fromEmail = 'noreply@' . str_replace ( "www.", "", $GLOBALS['HTTP_HOST'] );
							$body= $SMARTY->fetch('email-confirmation.tpl');
							$subject ='澳睿跑 (Ready Steady Go Kids) Payment Received';
							if($mailID = sendMail($to, $from, $fromEmail, $subject, $body, $bcc, $userArr['id'], $_SESSION['user']['admin']["id"])){
								$pay_obj->SetInvoiceEmail($paymentId, $mailID);
							}
						}catch(Exception $e){
							$error = 'Error: Confirmation email cannot be sent - ' .$e;
							$to = "readysteadygokids@gmail.com-dev,online@them.com.au";
							sendMail($to, $from, $fromEmail, 'Error: Confirmation email cannot be sent - admin area(D)', "Message: {$e}");
							break;
						}
							
						$ConfirmationMessage = "The payment was approved.";
						$SMARTY->assign('message',$ConfirmationMessage);
						$SMARTY->assign('hideReloadBtn',true);
						$template= $SMARTY->fetch('checkout-completed.tpl');
						echo json_encode(array(
								"error" => null,
								"success" => true,
								"template" => $template
						));
						exit;
							
					} else {
						$error = $pay_obj->GetErrorMessage();
						$error = !empty($error)? $error : 'Payment failed. Verify information and try again. ';
					}
				} else {
					$error = 'Payment failed: Missing fields. Please refresh the page.';
				}
					
				echo json_encode(array(
						"error" => $error,
						"success" => false
				));
				exit;
		}
	}
	echo json_encode(array("error"=>$error));
	die();
}








